<template>
  <load-more v-if="comment" ref="listRef" :enable-refresh="false" @load="handleLoad">
    <comment-item
      class="commenter"
      :comment="comment"
      :reply-show="false"
    />
    <p class="count">相关回复共 {{comment.rcount}} 条</p>
    <comment-item
      v-for="item in list"
      :key="item.rpid"
      :comment="item"
      :reply-show="false"
    />
  </load-more>
</template>

<script>
import { reactive, watch, toRefs } from 'vue'
import { Toast } from 'vant'
import CommentItem from './item'
import LoadMore from '@/components/LoadMore'
import { commentApi } from '@/api'
export default {
  name: 'CommentReply',
  components: {
    CommentItem,
    LoadMore
  },
  props: {
    // 评论数据
    comment: {
      type: Object
    }
  },
  setup(props) {
    const params = reactive({
      listRef: null,
      pageNum: null,
      list: []
    })
    
    const getData = async () => {
      try {
          const { code, data } = await commentApi.getMoreReply({
            oid: props.comment.oid,
            type: props.comment.type,
            root: props.comment.rpid,
            min_id: params.pageNum
          })
          if (code === 0 && data) {
            const { root: { replies }, cursor } = data
            const minId = cursor.min_id
            const allCount = cursor.all_count
            const maxId = cursor.max_id
            for (const reply of replies) {
              const { rpid } = reply
              const matchIndex = params.list.findIndex(re => re.rpid === rpid)
              if (matchIndex < 0) {
                params.list.push(reply)
              }
            }
            params.pageNum = maxId              
            if (minId >= allCount) {
              complete()
            }
          } else {
            complete()
          }
      } catch (error) {
        Toast.fail(error.message)
      }
      stopLoading()
    }

    const stopLoading = () => {
      params.listRef?.stopLoad()
    }

    const complete = () => {
      params.listRef?.completeLoad()
    }

    const isComplete = () => {
      return params.listRef?.isComplete()
    }

    const reset = () => {
      params.listRef?.reset()
    }

    const handleLoad = () => {
      if (!isComplete()) {
        getData()
      }
    }

    watch(() => props.comment, () => {
      reset()
      params.list = []
      getData()
    }, {
      immediate: true
    })

    return {
      ...toRefs(params),
      handleLoad
    }
  }
}
</script>

<style lang="scss" scoped>
  .commenter{
    margin-top: 0;
  }
  .count{
    font-size: 12px;
    color: $color-text-secondary;
    margin: 0;
    height: 30px;
    line-height: 30px;
  }
</style>